<template>
  <div class="main">
    <transition appear name="animate__animated animate__backInDown" enter-active-class="animate__backInDown"
      leave-active-class="animate__backOutDown">
      <component v-if="mainStore.loginState" :is="mainStore.layout">
        <router-view v-slot="{ Component }">
          <div class="page_view">
            <component :is="Component" v-if="mainStore.systemComplete" />
          </div>
        </router-view>
      </component>
      <login v-else></login>
    </transition>
  </div>
</template>

<script lang="tsx" setup>
import { useMainStore } from "@/store";
import Login from "./login.vue";
import { useNotification } from 'naive-ui';
import { watch } from "vue";
import { format } from 'date-fns'

let noti = useNotification();
let socket = null;

const env = import.meta.env;

const SocketConnact = () => {
  socket = new WebSocket(env.VITE_WEBSOCKET_URL + '/v1/order/websocket/server/' + mainStore.userInfo.id);
  socket.onopen = () => {
    console.log('订单系统连接成功');
  };
  socket.onmessage = data => {
    let msg = data.data;
    let date = new Date().getTime();

    noti.info({
      content: () => <div>{format(date, 'yyyy-MM-dd HH:mm:ss')}<br /><h3>{msg}</h3></div>,
      duration: 5000
    });
  };
  socket.onerror = () => {
    noti.error({
      content: "订单系统连接异常",
      duration: 5000
    });
  };
  socket.onclose = () => {
    noti.error({
      content: "订单系统关闭连接",
      duration: 5000
    });
  };
}

const mainStore = useMainStore();
if (mainStore.token) {
  mainStore.initSystem()
}

watch(() => mainStore.systemComplete, (v) => {
  if (v) {
    console.log('lianjie')
    SocketConnact();
  }
  else {
    socket.close();
  }
})
</script>

<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
  position: absolute;

  >div {
    width: 100%;
    height: 100%;
    position: absolute;
  }
}

.page_view {
  position: relative;
  padding: 20px;
  box-sizing: border-box;
}
</style>
